package com.github.springbootPlus.excel.result;

import com.github.springbootPlus.excel.parsing.ExcelError;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;

/**
 * Excel导入结果
 *
 * @author lisuo
 */
public class ExcelImportResult {

    int titleIndex = 0;


    /**
     * 头信息,标题行之前的数据,每行表示一个List<Object>,每个Object存放一个cell单元的值
     */
    private List<List<Object>> header = null;

    private List<String> title = null;

    /**
     * JavaBean集合,从标题行下面解析的数据
     */
    private List<?> listBean;

    /**
     * Errors
     */
    private List<ExcelError> errors = new ArrayList<ExcelError>();

    public List<List<Object>> getHeader() {
        return header;
    }

    public void setHeader(List<List<Object>> header) {
        this.header = header;
    }

    public List<String> getTitle() {
        return title;
    }

    public void setTitle(List<String> title) {
        this.title = title;
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> getListBean() {
        return (List<T>) listBean;
    }

    public void setListBean(List<?> listBean) {
        this.listBean = listBean;
    }

    public List<ExcelError> getErrors() {
        return errors;
    }

    public int getTitleIndex() {
        return titleIndex;
    }

    public void setTitleIndex(int titleIndex) {
        this.titleIndex = titleIndex;
    }

    public List<ExcelError> getSortedErrors() {
        HashSet<ExcelError> hashSet = new HashSet(errors);
        ExcelError[] errorsResult = hashSet.toArray(new ExcelError[]{});
        Arrays.sort(errorsResult, new Comparator<ExcelError>() {
            @Override
            public int compare(ExcelError o1, ExcelError o2) {
                return o1.getRow() - o2.getRow();
            }
        });
        return Arrays.asList(errorsResult);
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> getValidListBean() {
        if (listBean == null) return null;
        List<T> result = new ArrayList<>(listBean.size());
        for (int i = 0; i < listBean.size(); i++) {
            if (!isErrorRow(i)) {
                result.add((T) listBean.get(i));
            }
        }
        return (List<T>) result;
    }

    private boolean isErrorRow(int i) {
        for (ExcelError error : errors) {
            int idx = error.getRow() - (titleIndex + 1) - 1;
            if (i == idx) {
                return true;
            }
        }
        return false;
    }

    /**
     * 导入是否含有错误
     *
     * @return true:有错误,false:没有错误
     */
    public boolean hasErrors() {
        return CollectionUtils.isNotEmpty(errors);
    }

    /**
     * 导入是否有数据
     *
     * @return true:有 ,false:没有
     */
    public boolean hasData() {
        return CollectionUtils.isNotEmpty(listBean);
    }

}
